package com.lzp.aop.config;

import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

@Configuration
@Primary //在同样的DataSource中，首先使用被标注的DataSource
@Slf4j
public class DataSourceConfig {

    @Value("${spring.datasource.url}")
    private String datasourceUrl;
    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;

    @Bean     //声明其为Bean实例
    public DataSource dataSource() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(datasourceUrl);
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setConnectionTestQuery("select 1");

        //创建数据库
        Connection connection = null;
        Statement statement = null;
        try {
            Class.forName(driverClassName);
            String var1 = datasourceUrl.substring(0,datasourceUrl.indexOf("?"));
            String var2 = var1.substring(0,var1.lastIndexOf("/"));
            String database = var1.substring(var1.lastIndexOf("/")+1);
            String var3 = datasourceUrl.substring(datasourceUrl.indexOf("?"));
            String url = var2 + var3;
            connection = DriverManager.getConnection(url, username, password);
            statement = connection.createStatement();
            // 创建数据库
            statement.executeUpdate("create database if not exists `" + database + "` default character set utf8 COLLATE utf8_general_ci");
            statement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(statement != null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(connection != null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return dataSource;
    }
}